package com.example.demo.controller;

import com.example.demo.model.AppSetting;
import com.example.demo.model.Notice;
import com.example.demo.model.Torrent;
import com.example.demo.model.User;
import com.example.demo.service.*;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminController {
    private final AdminService adminService;
    private final JwtUtils jwtUtils;

    private final ReportService reportService;
    private final UserService userService;

    private final PromotionService promotionService;

    private final StoreService storeService;

    @Autowired
    public AdminController(AdminService adminService, JwtUtils jwtUtils, ReportService reportService, UserService userService, PromotionService promotionService, StoreService storeService) {
        this.adminService = adminService;
        this.jwtUtils = jwtUtils;
        this.reportService = reportService;
        this.userService = userService;
        this.promotionService = promotionService;
        this.storeService = storeService;
    }

    @PostMapping("/users/{userId}/ban")
    @PreAuthorize("hasRole('ADMIN')")
    public Response<String> banUser(
            @PathVariable Long userId,
            @RequestParam String reason,
            @RequestParam Long banDurationDays, // 新增封禁时长参数
            @RequestHeader("Authorization") String token) {

        try {
            // 检查 Token 格式
            if (token == null || !token.startsWith("Bearer ")) {
                return Response.badRequest("无效的令牌格式");
            }

            // 获取管理员用户名
            String adminUsername;
            try {
                adminUsername = jwtUtils.getUsernameFromToken(token.substring(7));
            } catch (Exception e) {
                return Response.unauthorized("令牌解析失败");
            }

            // 执行封禁
            String result = adminService.banUser(userId, reason, banDurationDays, adminUsername);
            return Response.success(result);

        } catch (IllegalArgumentException e) {
            return Response.badRequest(e.getMessage()); // 用户不存在
        } catch (IllegalStateException e) {
            return Response.badRequest(e.getMessage()); // 用户已封禁
        } catch (Exception e) {
            log.error("封禁操作异常", e);
            return Response.serverError("封禁失败: " + e.getMessage());
        }
    }

    @PostMapping("/users/{userId}/unban")
    @PreAuthorize("hasRole('ADMIN')")
    public Response<String> unbanUser(
            @PathVariable Long userId,
            @RequestHeader("Authorization") String token) {

        try {
            // 获取当前管理员用户
            String adminUsername;
            try {
                adminUsername = jwtUtils.getUsernameFromToken(token.substring(7));
            } catch (Exception e) {
                return Response.unauthorized("令牌解析失败");
            }

            // 执行解封操作
            String result = adminService.unbanUser(userId, adminUsername);
            return Response.success(result);
        } catch (Exception e) {
            return Response.serverError("解封操作失败: " + e.getMessage());
        }
    }



    @PostMapping("/report/process")
    public ResponseEntity<?> processReport(@RequestParam Long reportId,
                                           @RequestParam String processResult,
                                           @RequestParam Integer actionTaken,
                                           Authentication authentication) {
        Long adminId = Long.parseLong(authentication.getName());
        reportService.processReport(reportId, adminId, processResult, actionTaken);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/promotions")
    public ResponseEntity<String> createPromotion(
            @RequestParam Long torrentId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {

        promotionService.setupPromotion(torrentId, startTime, endTime);
        return ResponseEntity.ok("促销活动设置成功");
    }

    @PostMapping("/del-promotions")
    public ResponseEntity<String> closePromotion(@RequestParam Long torrentId) {
        promotionService.closePromotion(torrentId);
        return ResponseEntity.ok("促销活动删除成功");
    }

    @GetMapping("/promotions/active")
    public ResponseEntity<List<Torrent>> getActivePromotions() {
        return ResponseEntity.ok(promotionService.getActivePromotions());
    }

    @PostMapping("/store")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response<Map<String, Object>> addProduct(
            @RequestParam String name,
            @RequestParam(required = false) String description,
            @RequestParam int price,
            @RequestParam String type,
            @RequestParam(required = false, defaultValue = "0") int duration,
            @RequestParam(required = false, defaultValue = "-1") int stock) {
        return Response.success(storeService.addProduct(name, description, price, type, duration, stock));
    }

    @PutMapping("/store/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response<Map<String, Object>> updateProduct(
            @PathVariable("id") Long productId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) Integer price,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer duration,
            @RequestParam(required = false) Integer stock) {
        return Response.success(storeService.updateProduct(productId, name, description, price, type, duration, stock));
    }

    @DeleteMapping("/store/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response<Map<String, Object>> deleteProduct(@PathVariable("id") Long productId) {
        return Response.success(storeService.deleteProduct(productId));
    }

    @GetMapping("/store")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response<Map<String, Object>> getAllProducts() {
        return Response.success(storeService.getAllProducts());
    }

    @PostMapping("/notice")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<Notice> publishNotice(
            @RequestParam Long adminId,
            @RequestParam String topic,
            @RequestParam String content) {
        Notice notice = adminService.publishNotice(adminId, topic, content);
        return ResponseEntity.ok(notice);
    }

    // 查询所有通知列表
    @GetMapping("/notice")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<List<Notice>> getNotices() {
        try {
            List<Notice> notices = adminService.getAllNotices();
            return ResponseEntity.ok(notices);
        } catch (Exception e) {
            log.error("查询通知失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @DeleteMapping("/notice/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<Void> deleteNotice(@PathVariable Long id) {
        adminService.deleteNotice(id);
        return ResponseEntity.noContent().build();
    }

    @PostMapping("/config-setting")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<AppSetting> configureSystemParam(
            @RequestParam String configKey,
            @RequestParam Double configValue) {
        try {
            AppSetting config = adminService.configureSystemParam(configKey, configValue);
            return ResponseEntity.ok(config);
        } catch (Exception e) {
            log.error("配置系统参数失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    @GetMapping("/config-select")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<List<AppSetting>> getAllSystemParam() {
        try {
            List<AppSetting> settings = adminService.getAllSystemParam();
            return ResponseEntity.ok(settings);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    //获取待审种子
    @GetMapping("/torrents/pending")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<List<Torrent>> getPendingTorrents() {
        try {
            List<Torrent> torrents = adminService.getPendingTorrents();
            return ResponseEntity.ok(torrents);
        } catch (Exception e) {
            log.error("查询待审种子失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    //审核种子
    @PostMapping("/torrents/review")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Response<String> reviewTorrent(
            @RequestParam Long torrentId,
            @RequestParam Integer status,
            Authentication authentication) {
        try {
            Long adminId = Long.parseLong(authentication.getName());
            String result = adminService.reviewTorrent(torrentId, status, adminId);
            return Response.success(result);
        } catch (IllegalArgumentException e) {
            return Response.badRequest(e.getMessage());
        } catch (Exception e) {
            log.error("审核种子失败", e);
            return Response.serverError("审核失败: " + e.getMessage());
        }
    }

    @GetMapping("/users")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<List<User>> getAllUsers() {
        try {
            List<User> users = adminService.getAllUsers();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            log.error("查询所有用户信息失败", e);
            return ResponseEntity.status(500).body(null);
        }
    }

}